from django.shortcuts import render
from rest_framework import status
from rest_framework.decorators import action
from rest_framework.generics import CreateAPIView,UpdateAPIView
from rest_framework.response import Response
from rest_framework.views import APIView

from users.models import User,Address
from users.serializers import CreateUserSerializer,EmailSerializer,UserAddressSerializer,AddressTitleSerializer
from rest_framework.permissions import IsAuthenticated
from .utils import check_verify_email_token
from rest_framework.viewsets import ModelViewSet
from .import constants


class UsernameCountView(APIView):
    def get(self,request,username):
        '''
        获取指定用户名的数量
        :param request: 请求对象
        :param username: 用户名
        :return: 用户名以及数量
        '''
        #根据用户到数据库中查询数量
        count=User.objects.filter(username=username).count()
        #响应信息
        data={
            'username':username,
            'count':count,

        }
        return Response(data)

class MobileCountView(APIView):
    def get(self,request,mobile):
        '''
        获取指定手机号的数量
        :param request: 请求对象
        :param mobile: 手机号
        :return: 手机号以及数量
        '''
        #根据手机号到数据库中查询数量
        count=User.objects.filter(mobile=mobile).count()
        #响应信息
        data={
            'mobile':mobile,
            'count':count,
        }
        return Response(data)

class UserView(CreateAPIView):
    '''用户视图'''
    serializer_class = CreateUserSerializer

class UserDetailView(APIView):
    '''用户信息视图'''
    #权限判断【这个页面必须是登录后的用户才能访问到】
    permission_classes = [IsAuthenticated]

    def get(self,request):
        #获取当前登录用户【request.user 获取当前已经登录的用户了】
        user=request.user

        #响应数据
        return Response({
            'id':user.id,
            'username':user.username,
            'mobile':user.mobile,
            'email':user.email
        })

class EmailView(UpdateAPIView):
    #用户邮箱保存视图

   permission_classes = [IsAuthenticated]
   serializer_class = EmailSerializer

   def get_object(self):
       '''因为地址栏上面没有pk这个url参数所以我们需要重写get_object获取指定的用户信息'''
       return self.request.user



class VerifyEmailView(APIView):
    '''更新邮箱激活状态视图'''
    def get(self,request):
        #1.获取token提取里面的user.id
        try:
            token=request.query_params.get('token')
        except Exception:
            return Response({'message':'无效的token'},status=status.HTTP_400_BAD_REQUEST)
        user_id=check_verify_email_token(token)

        if user_id is None:
            return Response({'message':'无效的token'},status=status.HTTP_400_BAD_REQUEST)
        #2.根据id获取用户信息
        try:
            #pk表示当前模型中的主键字段
            user=User.objects.get(pk=user_id)
        except :
            return Response({'message':'无效的token'},status=status.HTTP_400_BAD_REQUEST)
        #3.修改用户的邮箱激活状态
        user.email_active=True
        user.save()
        #4.响应数据
        return Response({'message':'OK'},status=status.HTTP_200_OK)




class AddressesViewSet(ModelViewSet):
    '''用户的收货地址视图集'''
    permission_classes=[IsAuthenticated]
    serializer_class = UserAddressSerializer
    queryset = Address.objects.filter(is_deleted=False)

    def list(self,request,*args,**kwargs):
        queryset=self.get_queryset()
        serializer=self.get_serializer(queryset,many=True)

        user =self.request.user
        return Response({
            "limit": constants.USER_ADDRESS_COUNTS_LIMIT,
            'default_address_id':user.default_address,
            'addresses':serializer.data
        })

    # def update(self, request, *args, **kwargs):
    #     queryset=Address.objects.filter(is_deleted=False,pk=id)
    #     seriazlizer=self.get_serializer(data=queryset)
    #
        # return Response({
        #
        # })


    def create(self, request, *args, **kwargs):
        '''保存用户地址数据'''
        #检查用户地址数据不能超过上限
        count=request.user.addresses.count()
        if count >= constants.USER_ADDRESS_COUNTS_LIMIT:
            return Response({'message':'保存地址数据已达到上限'},status=status.HTTP_400_BAD_REQUEST)
        return super().create(request,*args,**kwargs)

    def destroy(self, request, *args, **kwargs):
        '''处理删除'''
        #本次请求中pk值对应的收货地址
        address=self.get_object()
        #进行逻辑删除
        address.is_deleted=True
        address.save()
        return Response(status=status.HTTP_204_NO_CONTENT)

    @action(methods=['put'],detail=True)
    def status(self,request,pk=None):
        '''设置默认地址'''
        address=self.get_object()
        request.user.default_address=address
        request.user.save()
        return Response({'message':'OK'},status=status.HTTP_200_OK)
    @action(methods=['put'],detail=True)
    def title(self,request,pk=None):
        '''修改标题'''
        address=self.get_object()
        serializer=AddressTitleSerializer(instance=address,data=request.data)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        return Response(serializer.data)